<?php


namespace app\controller\api;


use app\BaseController;
use app\common\Consts;
use app\models\config\ArticleModel;
use app\models\config\ConfigModel;
use app\models\goods\CategoryModel;
use app\models\goods\GoodsModel;
use app\Request;
use app\services\config\ConfigService;
use app\services\delivery\CupboardService;
use app\services\delivery\DeliveryService;
use app\services\delivery\GoodsService;
use app\services\user\AdminUserService;
use think\facade\Cache;
use think\facade\Db;

class IndexController extends BaseController
{
    public function getFreight(){
        $freight = ConfigService::getConfigValue('freight');
        return $this->success($freight);
    }

    public function indexBase(){
        $logo = ConfigService::getConfigValue('logo');
        $site_title = ConfigService::getConfigValue('site_title');
        $download_url = ConfigService::getConfigValue('download_url');
        $version = ConfigService::getConfigValue('version');
        $share_url = ConfigService::getConfigValue('share_url');
        return $this->success(['logo' => $logo,'site_title' => $site_title,'version' => $version,'download_url' => $download_url,'share_url' => $share_url]);
    }

    public function indexdata()
    {
        try {
            $data['banner_list'] = json_decode(Db::name('config')->where('config_key', 'banner_list')->value('config_content'),true);
            //$data['tips'] = ArticleModel::order('id','desc')->find();

            //金刚区
            $category = Db::name('category')->field('id,title,img')->where(['status' => 0,'pid' => 0])->order('sort desc')->select();
            $data['category'] = $category;

            //返回第一个分类下的商品
            $goods = [];
            if($category){
                $goods = Db::name('goods')->field('id,image,name,sell_price,sales,green_scores')
                    ->where('status',1)
                    ->where('category_id',$category[0]['id'])
                    
                    ->select();
            }
            $data['goods'] = $goods;


            return $this->success($data);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }



    /**
     * 公告列表
     * @return \think\response\Json
     */
    public function articleList()
    {
        try {
            $list = ArticleModel::paginate(['list_rows' => $this->limit, 'page' => $this->page])->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 公告详情
     * @return \think\response\Json
     */
    public function articleInfo()
    {
        try {
            $id = $this->request->param('id');
            $info = ArticleModel::find($id);
            $info->num = Db::raw('num+1');
            $info->save();
            return $this->success($info);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 首页配置
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        try {
            $config = Cache::get('web_config');
            if (!$config) {
                $config = Db::name('config')->where('key', 'web_site_config')->value('context');
                Cache::set('web_config', $config);
            }
            $res = json_decode($config, true);
            return $this->success($res);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 预约
     */
    public function appoint()
    {
        Db::startTrans();
        try {
            $userId = $this->request->userId;
            $paintId = $this->request->param('paint_id');
            $paintInfo = Db::name('paint')->where('paint_code', $paintId)->find();
            if (!$paintInfo) {
                throw new \Exception('店铺不存在');
            }
            if ($paintInfo['status'] == 0) {
                throw new \Exception('预约已关闭');
            }
            $priceType = $this->request->param('price_type');
            if (!in_array($priceType, [1, 2, 3])) {
                throw new \Exception("预约价格范围错误");
            }
            $key = "appoint_" . $userId . '_' . $paintId . '_' . $priceType;
            if (Cache::get($key)) {
                throw new \Exception("请勿重复点击");
            }
            Cache::set($key, 1, 3);
            if ($priceType == 1) {
                $minPrice = 2000;
                $maxPrice = 3000;
            } elseif ($priceType == 2) {
                $minPrice = 3001;
                $maxPrice = 6000;
            } else {
                $minPrice = 6001;
                $maxPrice = 0;
            }
            $res = Db::name('appoint')
                ->where('user_id', $userId)
                ->where('min_price', $minPrice)
                ->where('create_time', '>=', strtotime(date('Y-m-d')))
                ->find();
            if ($res) {
                throw new \Exception("今日已预约过");
            }
            Db::name('appoint')->insert([
                'user_id' => $userId,
                'order_sn' => 'Y' . date("YmdHis") . rand(10000, 99999),
                'min_price' => $minPrice,
                'max_price' => $maxPrice,
                'create_time' => time(),
                'update_time' => time(),
            ]);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 预约记录
     */
    public function appointRecord()
    {
        try {
            $userId = $this->request->userId;
            $where = [];
            $where[] = ['user_id', '=', $userId];
            $type = $this->request->param('type');
            if ($type == 1) {
                $time = date('Y-m-d 00:00:00');
                $where[] = ['create_time', '>=', $time];
            }
            $res = Db::name('appoint')
                ->where($where)
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            foreach ($res['data'] as &$v) {
                $v['create_time'] = date('Y-m-d\TH:i:s', $v['create_time']);
            }
            return $this->success($res);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function getUserSetting()
    {
        $userId = $this->request->userId;
        $paymentInfo = Db::name('user_payment')->where('customer_id', $userId)->find();
        if (!$paymentInfo) {
            $this->success(1);
        }
        $addressInfo = Db::name('user_address')->where('user_id', $userId)->find();
        if (!$addressInfo) {
            $this->success(2);
        }
        return $this->success(0);
    }

    public function getCateList()
    {
        try {
            $res = Db::name('type')
                ->field('id,title')
                ->select();
            return $this->success($res);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }


    public function getTypeList()
    {
        try {
            $res = Db::name('category')
                ->field('id,title')
                ->select();
            return $this->success($res);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function getItemList()
    {
        try {
            $where = [];
            $where[] = ['status', '=', 0];
            $search = $this->request->param('search');
            if ($search) {
                $where[] = ['title', 'like', '%' . $search . '%'];
            }
            $type = $this->request->param('type_id');
            if ($type) {
                $where[] = ['type_id', '=', $type];
            }
            $cate = $this->request->param('cate_id');
            if ($cate) {
                $where[] = ['cate_id', '=', $cate];
            }
            $res = Db::name('article')
                ->field('id,type_id,title,img,intro')
                ->where($where)
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            return $this->success($res);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function getItemInfo()
    {
        try {
            $id = $this->request->param('id');
            $res = Db::name('article')
                ->where('id', $id)
                ->find();
            return $this->success($res);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function setUserNeed()
    {
        try {
            $username = $this->request->param('username', '未知', 'trim');
            $mobile = $this->request->param('mobile');
            if (!$mobile) {
                throw new \Exception('请填写您的联系方式');
            }
            $fee = $this->request->param('fee');
            $need = $this->request->param('need');

            Db::name('user_need')->insert([
                'username' => $username,
                'mobile' => $mobile,
                'need' => $need,
                'fee' => $fee,
                'create_time' => date('Y-m-d H:i:s')
            ]);
            $msg = "客户:{$username}\n联系方式:{$mobile}\n预算:{$fee}\n需求:{$need}\n提醒:请及时处理!";
            $res = $this->sendDingDingMsg($msg);
            return $this->success($res);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function sendDingDingMsg($msg)
    {
        $config = Db::name('config')->where('key', 'web_site_config')->value('context');
        $config = json_decode($config, true);
        $time = intval(microtime(true) * 1000);
//        $secret = 'SECed481b6b74a4392c1409abcf596481893138ab08840a3bcb598057078ccb47fa';
        $secret = $config['secret'];
        $sign = urlencode(base64_encode(hash_hmac('sha256', "{$time}\n{$secret}", $secret, true)));
        // 钉钉机器人Webhook地址
//        $webhook = "https://oapi.dingtalk.com/robot/send?access_token=d083ca390874573948ee410f78910a35b9fad39ffae2a526d669f8fe76e068d9&timestamp=$time&sign=$sign";
//        $webhook = "https://oapi.dingtalk.com/robot/send?access_token=1617d76245449b916e56475f8e42e969a323ea88b6263f7b23d93edb78c53558&timestamp=$time&sign=$sign";
        $webhook = $config['hook'];
        $webhook = $webhook . '&timestamp=' . $time . '&sign=' . $sign;
        // 要发送的消息内容
        $message = array(
            "msgtype" => "text",
            "text" => array(
                "content" => $msg
            )
        );
        // 将消息内容转换为JSON格式
        $message_string = json_encode($message);
        // 发送HTTP POST请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $webhook);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $message_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        var_dump($data);
        return $data;
    }


    /**
     * 分类列表
     * @return \think\response\Json
     */
    public function getCategoryList()
    {
        try {
            $list = CategoryModel::where('status', 0)
                ->field('id,pid,title,img,sort')
                ->order('pid asc,sort asc')
                ->select()
                ->toArray();
            $tree = buildTree($list);
            return $this->success(array_reverse($tree));
        }catch(\Exception $exception){
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 政策协议
     */
    public function getProtocol()
    {
        try{
            //联系我们
            $contact_us = ConfigService::getConfigValue('contact_us');;

            //推广规则
            $promotion_rules = ConfigService::getConfigValue('promotion_rules');;


            //用户协议
            $user_agreement = ConfigService::getConfigValue('user_agreement');;

            //关于我们
            $about_us = ConfigService::getConfigValue('about_us');

            //隐私政策
            $privacy_policy = ConfigService::getConfigValue('privacy_policy');

            $data = [
                'contact_us' => $contact_us,
                'promotion_rules' => $promotion_rules,
                'user_agreement' => $user_agreement,
                'about_us' => $about_us,
                'privacy_policy' => $privacy_policy,
            ];
            return $this->success($data);
        }catch(\Exception $exception){
            return $this->error($exception->getMessage());
        }
    }

    public function getPolicy()
    {
        try{
            $type = $this->request->param('type',1);

            switch($type){
                case 1:
                    $data = ConfigService::getConfigValue('contact_us');    //联系我们
                break;
                case 2:
                    $data = ConfigService::getConfigValue('promotion_rules');    //推广规则
                    break;
                case 3:
                    $data = ConfigService::getConfigValue('user_agreement');    //用户协议
                    break;
                case 4:
                    $data = ConfigService::getConfigValue('about_us');    //关于我们
                    break;
                case 5:
                    $data = ConfigService::getConfigValue('privacy_policy');    //隐私政策
                    break;
                case 6:
                    $data = ConfigService::getConfigValue('service_privacy_terms');    //服务与隐私条款
                    break;
                    $data = '';
            }

            return $this->success($data);
        }catch(\Exception $exception){
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 检测版本号
     * @return \think\response\Json
     */
    public function checkVersion()
    {
        try {
            $tokenType = $this->request->header('token-type');
            if ($tokenType == 1) {
                return $this->success();
            }
            $version = $this->request->param('version', '0.0.0');
            $configVersion = ConfigService::getConfigValue('version');
            if (version_compare($version, $configVersion) == -1) {
                $downloadUrl = ConfigService::getConfigValue('download_url');
                return $this->success($downloadUrl, '版本号过低', -2);
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function getConfig()
    {
        $res = ConfigService::getConfigValueArray(['logo', 'site_title','download_url']);
        return $this->success($res);
    }
}